<template>
  <div class="question-edit-dialog">
    <div class="dialog-overlay" @click.self="close">
      <div class="dialog-container">
        <div class="dialog-header">
          <h3>编辑题目</h3>
          <div class="header-actions">
            <span class="question-type-badge" :style="{ backgroundColor: typeColor }">
              {{ questionTypeName }}
            </span>
            <button class="close-btn" @click="close">
              <i class="fas fa-times"></i>
            </button>
          </div>
        </div>

        <div class="dialog-body">
          <div class="form-row">
            <div class="form-group type-selector">
              <label>题目类型</label>
              <div class="type-options">
                <button
                    v-for="type in typeOptions"
                    :key="type.value"
                    class="type-option"
                    :class="{ active: form.type === type.value }"
                    @click="handleTypeChange(type.value)"
                >
                  <i :class="['fas', type.icon]"></i>
                  <span>{{ type.label }}</span>
                </button>
              </div>
            </div>

            <div class="form-group difficulty-selector">
              <label>难度</label>
              <div class="difficulty-slider">
                <div class="slider-labels">
                  <span>简单</span>
                  <span>中等</span>
                  <span>困难</span>
                </div>
                <input
                    type="range"
                    v-model="form.difficulty"
                    min="1"
                    max="10"
                    step="1"
                    class="slider-input"
                    :style="{
                    '--track-color': difficultyGradient,
                    '--thumb-color': difficultyColor
                  }"
                >
                <div class="slider-value">
                  <span class="value-badge" :style="{ backgroundColor: difficultyColor }">
                    {{ form.difficulty }}
                  </span>
                  <span class="level-text">{{ difficultyLevel }}</span>
                </div>
              </div>
            </div>
          </div>

          <div class="form-group">
            <label>题目内容 <span class="required">*</span></label>
            <div class="rich-text-editor">
              <textarea
                  v-model="form.content"
                  class="question-content"
                  placeholder="请输入题目内容..."
                  rows="4"
              ></textarea>
            </div>
          </div>

          <div class="form-group" v-if="showOptions">
            <div class="options-header">
              <label>题目选项 <span class="required">*</span></label>
              <button
                  class="btn-add-option"
                  @click="addOption"
                  :disabled="options.length >= maxOptions"
              >
                <i class="fas fa-plus"></i> 添加选项
              </button>
            </div>

            <draggable
                v-model="options"
                handle=".drag-handle"
                @end="onOptionSort"
            >
              <div
                  v-for="(option, index) in options"
                  :key="index"
                  class="option-item"
                  :class="{ 'is-correct': isCorrectOption(form, option.key) }"
              >
                <div class="option-key-wrapper">
                  <span class="drag-handle">
                    <i class="fas fa-grip-vertical"></i>
                  </span>
                  <input
                      v-model="option.key"
                      type="text"
                      class="option-key"
                      maxlength="1"
                      @input="validateOptionKey(index)"
                  >
                </div>
                <div class="option-text-wrapper">
                  <textarea
                      v-model="option.text"
                      class="option-text"
                      placeholder="请输入选项内容..."
                      rows="2"
                  ></textarea>
                </div>
                <div class="option-actions">
                  <button
                      class="btn-mark-correct"
                      @click="toggleCorrectAnswer(option.key)"
                      :title="isCorrectOption(form, option.key) ? '取消正确答案' : '设为正确答案'"
                  >
                    <i class="fas" :class="isCorrectOption(form, option.key) ? 'fa-check-circle' : 'fa-circle'"></i>
                  </button>
                  <button
                      class="btn-remove-option"
                      @click="removeOption(index)"
                      :disabled="options.length <= minOptions"
                      title="删除选项"
                  >
                    <i class="fas fa-trash-alt"></i>
                  </button>
                </div>
              </div>
            </draggable>
          </div>

          <div class="form-group" v-if="showCorrectAnswer">
            <label>正确答案 <span class="required">*</span></label>
            <div class="correct-answers">
              <div v-if="form.type === '0'" class="single-choice-answers">
                <div class="answer-options">
                  <div
                      v-for="(option, index) in options"
                      :key="index"
                      class="answer-option"
                      :class="{ selected: isCorrectOption(form, option.key) }"
                      @click.stop="toggleCorrectAnswer(option.key)"
                  >
                    <div class="option-key">{{ option.key }}</div>
                    <div class="option-preview">{{ option.text || '选项' + (index + 1) }}</div>
                  </div>
                </div>
              </div>

              <div v-if="form.type === '1'" class="multi-choice-answers">
                <div class="answer-options">
                  <div
                      v-for="(option, index) in options"
                      :key="index"
                      class="answer-option"
                      :class="{ selected: isCorrectOption(form, option.key) }"
                      @click.stop="toggleCorrectAnswer(option.key)"
                  >
                    <div class="option-key">{{ option.key }}</div>
                    <div class="option-preview">{{ option.text || '选项' + (index + 1) }}</div>
                  </div>
                </div>
              </div>

              <div v-if="form.type === '3'" class="judgment-answers">
                <div class="judgment-options">
                  <div
                      class="judgment-option true-option"
                      :class="{ selected: isJudgmentTrueSelected }"
                      @click="setJudgmentAnswer('A')"
                  >
                    <div class="judgment-icon">
                      <i class="fas fa-check"></i>
                    </div>
                    <div class="judgment-label">正确</div>
                  </div>
                  <div
                      class="judgment-option false-option"
                      :class="{ selected: isJudgmentFalseSelected }"
                      @click="setJudgmentAnswer('B')"
                  >
                    <div class="judgment-icon">
                      <i class="fas fa-times"></i>
                    </div>
                    <div class="judgment-label">错误</div>
                  </div>
                </div>
              </div>

              <div v-if="form.type === '2'" class="fill-blank-answer">
                <div class="answer-input">
                  <input
                      v-model="form.correctAnswer"
                      type="text"
                      placeholder="请输入正确答案..."
                  >
                </div>
              </div>
            </div>
          </div>

          <div class="form-group">
            <label>答案解析 <span class="required">*</span></label>
            <div class="rich-text-editor">
              <textarea
                  v-model="form.parse"
                  class="question-parse"
                  placeholder="请输入答案解析..."
                  rows="4"
              ></textarea>
            </div>
          </div>
        </div>

        <div class="dialog-footer">
          <button class="btn btn-secondary" @click="close">
            <i class="fas fa-times"></i> 取消
          </button>
          <button class="btn btn-primary" @click="save" :disabled="isSaving">
            <i class="fas fa-save"></i> {{ isSaving ? '保存中...' : '保存更改' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import { toOptionsKV, formatAnswer, isCorrectOption, normalizeCorrectAnswer } from '@/utils/questionUtils';

export default {
  name: 'QuestionEditDialog',
  components: {
    draggable
  },
  props: {
    question: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      form: {
        type: '0',
        content: '',
        options: '',
        correctAnswer: '',
        parse: '',
        difficulty: 5
      },
      options: [
        { key: 'A', text: '' },
        { key: 'B', text: '' },
        { key: 'C', text: '' },
        { key: 'D', text: '' }
      ],
      minOptions: 2,
      maxOptions: 8,
      isSaving: false,
      typeOptions: [
        { value: '0', label: '单选题', icon: 'fa-dot-circle', color: '#4361EE' },
        { value: '1', label: '多选题', icon: 'fa-check-square', color: '#3A0CA3' },
        { value: '2', label: '填空题', icon: 'fa-pen', color: '#10B981' },
        { value: '3', label: '判断题', icon: 'fa-balance-scale', color: '#F59E0B' },
        { value: '4', label: '简答题', icon: 'fa-align-left', color: '#EF4444' }
      ]
    }
  },
  computed: {
    questionTypeName() {
      const type = this.typeOptions.find(t => t.value === this.form.type)
      return type ? type.label : '未知类型'
    },
    typeColor() {
      const type = this.typeOptions.find(t => t.value === this.form.type)
      return type ? type.color : '#6B7280'
    },
    difficultyLevel() {
      const difficulty = parseInt(this.form.difficulty)
      if (difficulty <= 3) return '简单'
      if (difficulty <= 7) return '中等'
      return '困难'
    },
    difficultyColor() {
      const difficulty = parseInt(this.form.difficulty)
      if (difficulty <= 3) return '#10B981'
      if (difficulty <= 7) return '#F59E0B'
      return '#EF4444'
    },
    difficultyGradient() {
      return `linear-gradient(to right, #10B981 0%, #10B981 35%, #F59E0B 35%, #F59E0B 65%, #EF4444 65%, #EF4444 100%)`
    },
    showOptions() {
      return ['0', '1'].includes(this.form.type)
    },
    showCorrectAnswer() {
      return this.form.type !== '4'
    },
    isJudgmentTrueSelected() {
      return this.form.type === '3' &&
          (this.form.correctAnswer === 'A' || this.form.correctAnswer === '正确')
    },
    isJudgmentFalseSelected() {
      return this.form.type === '3' &&
          (this.form.correctAnswer === 'B' || this.form.correctAnswer === '错误')
    }
  },
  created() {
    this.initFormData()
  },
  methods: {
    initFormData() {
      this.form = {
        ...this.question,
        type: this.question.type.toString(),
        difficulty: this.question.difficulty || 5,
        bankId: this.question.bankId.toString()
      }

      if (this.form.type === '3') {
        if (this.form.correctAnswer === '正确') {
          this.form.correctAnswer = 'A'
        } else if (this.form.correctAnswer === '错误') {
          this.form.correctAnswer = 'B'
        }
      }

      if (this.form.type === '1') {
        if (typeof this.form.correctAnswer === 'string') {
          this.form.correctAnswer = this.form.correctAnswer.split(',')
              .map(item => item.trim())
              .filter(Boolean)
        } else if (!Array.isArray(this.form.correctAnswer)) {
          this.form.correctAnswer = []
        }
      }

      if (this.showOptions) {
        let optionsArray = [];
        // 统一转为字符串，去掉首尾中括号
        let raw = String(this.form.options || '').replace(/^\[|\]$/g, '');
        // 分割并去除首尾引号
        const arr = raw.split(/[，,、\n]/).map(s => s.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean);
        optionsArray = arr.map((text, idx) => ({
          key: String.fromCharCode(65 + idx),
          text
        }));
        this.options = optionsArray;
      }
    },
    close() {
      this.$emit('close')
    },
    async save() {
      // 1. 表单验证
      if (!this.validateForm()) return;
      // 2. 检查是否有修改
      const isModified = this.checkQuestionModified();
      if (!isModified) {
        this.$message.info('题目内容未更改');
        return;
      }

      this.isSaving = true;

      try {
        // 准备数据时包含题目ID
        const formData = {
          ...this.form,
          questionId: this.question.questionId, // 确保传递题目ID
          options: this.options // 传递选项数组
        };
        // 发送保存请求F
        this.$emit('save', formData);
      } catch (error) {
        console.error('保存失败:', error);
      } finally {
        this.isSaving = false;
      }
    },

    // 检查题目是否被修改
    checkQuestionModified() {
      // 获取原始题目数据
      const originalQuestion = this.question;

      // 比较基本字段
      const basicFields = ['type', 'content', 'parse', 'difficulty'];
      for (const field of basicFields) {
        if (String(this.form[field] || '').trim() !== String(originalQuestion[field] || '').trim()) {
          return true;
        }
      }

      // 比较正确答案
      if (this.form.type === '1') {
        // 多选题比较 - 归一化处理答案格式
        // 原始答案归一化
        let originalAnswers = [];
        if (Array.isArray(originalQuestion.correctAnswer)) {
          originalAnswers = originalQuestion.correctAnswer;
        } else if (typeof originalQuestion.correctAnswer === 'string') {
          originalAnswers = originalQuestion.correctAnswer.split(/[,，、]/).map(item => item.trim()).filter(Boolean);
        }
        
        // 当前答案归一化
        let currentAnswers = [];
        if (Array.isArray(this.form.correctAnswer)) {
          currentAnswers = this.form.correctAnswer;
        } else if (typeof this.form.correctAnswer === 'string') {
          currentAnswers = this.form.correctAnswer.split(/[,，、]/).map(item => item.trim()).filter(Boolean);
        }

        // 提取答案中的选项键（A、B、C、D等）
        const originalKeys = originalAnswers.filter(ans => /^[A-Z]$/.test(ans));
        const currentKeys = currentAnswers.filter(ans => /^[A-Z]$/.test(ans));
        
        // 如果两边的选项键数量不同，则认为有修改
        if (originalKeys.length !== currentKeys.length) {
          return true;
        }
        
        // 如果有任一选项键不在另一边，则认为有修改
        for (const key of originalKeys) {
          if (!currentKeys.includes(key)) {
            return true;
          }
        }
      } else {
        // 其他题型直接比较标准化后的字符串
        const originalAns = String(originalQuestion.correctAnswer || '').trim();
        const currentAns = String(this.form.correctAnswer || '').trim();
        if (originalAns !== currentAns) {
          return true;
        }
      }

      // 比较选项（如果是选择题）
      if (this.showOptions) {
        // 统一选项格式为纯文本数组
        let originalOptions = [];
        if (typeof originalQuestion.options === 'string') {
          try {
            const parsed = JSON.parse(originalQuestion.options.replace(/'/g, '"'));
            originalOptions = Array.isArray(parsed) ? parsed : originalQuestion.options.split(/[,，]/).map(s => s.trim());
          } catch {
            originalOptions = String(originalQuestion.options).split(/[,，]/).map(s => s.trim()).filter(Boolean);
          }
        } else if (Array.isArray(originalQuestion.options)) {
          originalOptions = originalQuestion.options;
        }
        
        // 获取当前选项的文本内容
        const currentOptions = this.options.filter(opt => opt.text.trim()).map(opt => opt.text.trim());
        
        // 如果选项数量不同，则认为有修改
        if (originalOptions.length !== currentOptions.length) {
          return true;
        }
        
        // 比较每个选项的文本内容
        for (let i = 0; i < originalOptions.length; i++) {
          const origOpt = String(originalOptions[i] || '').trim();
          const currOpt = String(currentOptions[i] || '').trim();
          if (origOpt !== currOpt) {
            return true;
          }
        }
      }

      return false;
    },


    validateForm() {
      if (!this.form.content.trim()) {
        this.showError('请输入题目内容')
        return false
      }

      if (this.showOptions) {
        const validOptions = this.options.filter(opt => opt.text.trim())
        if (validOptions.length < this.minOptions) {
          this.showError(`至少需要${this.minOptions}个有效选项`)
          return false
        }
      }

      if (this.showCorrectAnswer) {
        if (this.form.type === '1' &&
            (!Array.isArray(this.form.correctAnswer) || this.form.correctAnswer.length === 0)) {
          this.showError('请选择至少一个正确答案')
          return false
        } else if (this.form.type !== '1' && !this.form.correctAnswer) {
          this.showError('请选择或输入正确答案')
          return false
        }
      }

      if (!this.form.parse.trim()) {
        this.showError('请输入答案解析')
        return false
      }

      return true
    },
    showError(message) {
      this.$message.error(message);
    },
    handleTypeChange(type) {
      // 保存当前内容、解析和难度
      const { content, parse, difficulty } = this.form;

      // 重置表单，但保留重要信息
      this.form = {
        bankId: this.question.bankId,
        type,
        content,
        parse,
        difficulty,
        options: '',
        correctAnswer: type === '1' ? [] : ''
      };

      // 处理选项初始化
      if (['0', '1'].includes(type)) {
        // 如果是切换在选择题之间（单选<->多选），尝试保留已有选项
        if (['0', '1'].includes(this.form.type) && this.options.length > 0) {
          // 保留现有选项，但清空正确答案
          this.options = this.options.map(opt => ({ ...opt }));
        } else {
          // 否则初始化默认选项
          this.options = [
            { key: 'A', text: '' },
            { key: 'B', text: '' },
            { key: 'C', text: '' },
            { key: 'D', text: '' }
          ];
        }
      } else if (type === '3') {
        // 判断题初始化特殊选项
        this.options = [
          { key: 'A', text: '正确' },
          { key: 'B', text: '错误' }
        ];
      }

      // 如果是切换到填空题或简答题，清空选项
      if (['2', '4'].includes(type)) {
        this.options = [];
      }
    },
    addOption() {
      if (this.options.length >= this.maxOptions) return

      const lastChar = this.options[this.options.length - 1].key.charCodeAt(0)
      this.options.push({
        key: String.fromCharCode(lastChar + 1),
        text: ''
      })

      this.$nextTick(() => {
        const lastOptionInput = this.$el.querySelector('.option-item:last-child .option-text')
        if (lastOptionInput) {
          lastOptionInput.focus()
        }
      })
    },
    removeOption(index) {
      if (this.options.length <= this.minOptions) return

      const removedKey = this.options[index].key
      this.options.splice(index, 1)

      if (this.form.type === '0') {
        if (this.form.correctAnswer === removedKey) {
          this.form.correctAnswer = ''
        }
      } else if (this.form.type === '1') {
        const idx = this.form.correctAnswer.indexOf(removedKey)
        if (idx > -1) {
          this.form.correctAnswer.splice(idx, 1)
        }
      }
    },
    validateOptionKey(index) {
      const value = this.options[index].key
      if (!/^[A-Z]$/.test(value)) {
        this.options[index].key = value.charAt(0).toUpperCase().replace(/[^A-Z]/g, '')
      }
    },


    formattedOptions(options, questionType) {
      return toOptionsKV(options, questionType);
    },


    toggleCorrectAnswer(key) {
      // 单选题逻辑
      if (this.form.type === '0') {
        // 如果当前已经是正确答案，则取消选择
        if (this.isCorrectOption(this.form, key)) {
          this.form.correctAnswer = '';
        }
        // 否则设置为当前选项
        else {
          this.form.correctAnswer = key;
        }
      }

      // 多选题逻辑
      else if (this.form.type === '1') {
        // 确保correctAnswer始终是数组格式
        if (!Array.isArray(this.form.correctAnswer)) {
          // 如果不是数组，转换为数组
          const rawAnswer = this.form.correctAnswer || '';
          this.form.correctAnswer = typeof rawAnswer === 'string'
            ? rawAnswer.split(/[,，、]/).map(item => item.trim()).filter(Boolean)
            : [];
        }
        
        // 创建一个副本以保持响应式
        let correctAnswers = [...this.form.correctAnswer];
        
        // 检查当前选项是否已被选中（只检查选项键，不检查文本）
        const isCurrentlyCorrect = correctAnswers.includes(key);

        if (isCurrentlyCorrect) {
          // 仅移除选项键，不再同时移除文本
          correctAnswers = correctAnswers.filter(item => item !== key);
        } else {
          // 仅添加选项键，不再添加文本
          correctAnswers.push(key);
        }

        // 按字母顺序排序并去重，确保一致的格式
        this.form.correctAnswer = [...new Set(correctAnswers)].sort();
      }
      // 判断题逻辑
      else if (this.form.type === '3') {
        this.form.correctAnswer = key; // A或B
      }
      // 填空题和简答题不需要处理
    },


    setJudgmentAnswer(answer) {
      this.form.correctAnswer = answer
    },

    onOptionSort() {
      console.log('选项顺序已变更:', this.options.map(o => o.key))
    },
    isCorrectOption(form, optionKey) {
      const correct = form.correctAnswer;
      const option = this.options.find(opt => opt.key === optionKey);
      if (!option) return false;
      if (form.type === '0') {
        return correct === optionKey || correct === option.text;
      }
      if (form.type === '1') {
        const arr = Array.isArray(correct)
          ? correct
          : String(correct).split(/[，,、]/).map(s => s.trim()).filter(Boolean);
        return arr.includes(optionKey) || arr.includes(option.text);
      }
      return false;
    }
  }
}
</script>

<style lang="less" scoped>
// 现代配色方案
@primary: #4361EE;
@primary-light: #A5B4FC;
@primary-lighter: #E0E7FF;
@secondary: #3A0CA3;
@success: #10B981;
@warning: #F59E0B;
@danger: #EF4444;
@info: #3B82F6;
@gray-50: #F9FAFB;
@gray-100: #F3F4F6;
@gray-200: #E5E7EB;
@gray-300: #D1D5DB;
@gray-400: #9CA3AF;
@gray-500: #6B7280;
@gray-600: #4B5563;
@gray-700: #374151;
@gray-800: #1F2937;
@gray-900: #111827;

// 阴影
@shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
@shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
@shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
@shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
@shadow-2xl: 0 25px 50px -12px rgba(0, 0, 0, 0.25);

// 圆角
@radius-sm: 4px;
@radius-md: 6px;
@radius-lg: 8px;
@radius-xl: 12px;
@radius-full: 9999px;

// 过渡效果
@transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);

// 字体
@font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;

.question-edit-dialog {
  font-family: @font-family;
  color: @gray-800;

  .dialog-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 2000;
    background-color: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(4px);
    animation: fadeIn 0.3s ease-out;
  }

  .dialog-container {
    width: 90%;
    max-width: 900px;
    min-height: 700px;
    max-height: 90vh;
    background-color: white;
    border-radius: @radius-xl;
    box-shadow: @shadow-2xl;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    transform: translateY(20px);
    opacity: 0;
    animation: dialogEnter 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards;
  }

  .dialog-header {
    padding: 1.5rem 2rem;
    border-bottom: 1px solid @gray-200;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: white;
    position: relative;

    h3 {
      margin: 0;
      font-size: 1.5rem;
      font-weight: 600;
      color: @gray-900;
    }

    .header-actions {
      display: flex;
      align-items: center;
      gap: 1rem;
    }

    .question-type-badge {
      padding: 0.375rem 0.75rem;
      border-radius: @radius-full;
      font-size: 0.875rem;
      font-weight: 500;
      color: white;
      box-shadow: @shadow-sm;
    }

    .close-btn {
      background: none;
      border: none;
      font-size: 1.25rem;
      color: @gray-500;
      cursor: pointer;
      transition: @transition;
      width: 36px;
      height: 36px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      background-color: @gray-100;

      &:hover {
        color: @danger;
        background-color: @gray-200;
      }
    }
  }

  .dialog-body {
    flex: 1;
    overflow-y: auto;
    padding: 2rem;
    background-color: @gray-50;
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
  }

  .form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1.5rem;

    @media (max-width: 768px) {
      grid-template-columns: 1fr;
    }
  }

  .form-group {
    label {
      display: block;
      margin-bottom: 0.75rem;
      font-weight: 500;
      color: @gray-700;
      font-size: 0.9375rem;

      .required {
        color: @danger;
        margin-left: 4px;
      }
    }

    &.type-selector {
      .type-options {
        display: grid;
        grid-template-columns: repeat(5, 1fr);
        gap: 0.5rem;

        @media (max-width: 768px) {
          grid-template-columns: repeat(3, 1fr);
          grid-template-rows: auto auto;
        }

        .type-option {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 0.75rem 0.5rem;
          border-radius: @radius-md;
          border: 1px solid @gray-200;
          background-color: white;
          cursor: pointer;
          transition: @transition;
          font-size: 0.8125rem;
          color: @gray-600;
          box-shadow: @shadow-sm;

          i {
            font-size: 1.25rem;
            margin-bottom: 0.5rem;
            color: @gray-500;
          }

          &:hover {
            border-color: @primary-light;
            color: @primary;
            transform: translateY(-2px);
            box-shadow: @shadow-md;

            i {
              color: @primary;
            }
          }

          &.active {
            border-color: @primary;
            background-color: @primary-lighter;
            color: @primary;
            font-weight: 500;
            box-shadow: 0 0 0 1px @primary;

            i {
              color: @primary;
            }
          }
        }
      }
    }

    &.difficulty-selector {
      .difficulty-slider {
        .slider-labels {
          display: flex;
          justify-content: space-between;
          margin-bottom: 0.5rem;
          font-size: 0.8125rem;
          color: @gray-500;
        }

        .slider-input {
          width: 100%;
          height: 6px;
          border-radius: 3px;
          background: var(--track-color);
          -webkit-appearance: none;
          outline: none;
          margin: 15px 0;
          cursor: pointer;

          &::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: white;
            border: 2px solid var(--thumb-color);
            cursor: pointer;
            box-shadow: @shadow-md;
            transition: @transition;
          }

          &::-moz-range-thumb {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: white;
            border: 2px solid var(--thumb-color);
            cursor: pointer;
            box-shadow: @shadow-md;
            transition: @transition;
          }

          &:hover {
            &::-webkit-slider-thumb {
              transform: scale(1.1);
            }
            &::-moz-range-thumb {
              transform: scale(1.1);
            }
          }
        }

        .slider-value {
          display: flex;
          align-items: center;
          justify-content: center;
          margin-top: 8px;

          .value-badge {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 24px;
            height: 24px;
            line-height: 1;
            text-align: center;
            color: white;
            border-radius: @radius-full;
            font-size: 0.8125rem;
            font-weight: 600;
            padding: 0 8px;
            margin-right: 8px;
            box-shadow: @shadow-sm;
          }

          .level-text {
            font-size: 0.875rem;
            font-weight: 500;
            color: @gray-700;
          }
        }
      }
    }

    .rich-text-editor {
      position: relative;
      border-radius: @radius-md;
      box-shadow: @shadow-sm;
      transition: @transition;

      &:hover {
        box-shadow: @shadow-md;
      }

      &:focus-within {
        box-shadow: 0 0 0 3px fade(@primary, 20%);
      }
    }

    .question-content,
    .question-parse,
    .option-text {
      width: 100%;
      padding: 0.875rem 1rem;
      border: 1px solid @gray-300;
      border-radius: @radius-md;
      font-size: 0.9375rem;
      color: @gray-800;
      transition: @transition;
      background-color: white;
      resize: vertical;
      min-height: 80px;
      font-family: @font-family;
      line-height: 1.5;

      &:focus {
        outline: none;
        border-color: @primary;
        box-shadow: 0 0 0 3px fade(@primary, 20%);
      }

      &::placeholder {
        color: @gray-400;
        font-size: 0.875rem;
      }
    }

    .option-text {
      min-height: 60px;
    }

    .options-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 0.75rem;

      .btn-add-option {
        background: @primary;
        color: white;
        border: none;
        padding: 0.5rem 1rem;
        border-radius: @radius-md;
        font-size: 0.875rem;
        cursor: pointer;
        transition: @transition;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        box-shadow: @shadow-sm;
        font-weight: 500;

        &:hover {
          background: darken(@primary, 5%);
          box-shadow: @shadow-md;
          transform: translateY(-1px);
        }

        &:active {
          transform: translateY(0);
        }

        &:disabled {
          opacity: 0.5;
          cursor: not-allowed;
          background: @gray-400;
          transform: none;
        }

        i {
          font-size: 0.875rem;
        }
      }
    }

    .option-item {
      display: flex;
      align-items: center;
      gap: 0.75rem;
      padding: 0.75rem;
      border-radius: @radius-md;
      transition: @transition;
      background-color: white;
      border: 1px solid @gray-200;
      margin-bottom: 0.75rem;
      box-shadow: @shadow-sm;

      &:hover {
        border-color: @gray-300;
        box-shadow: @shadow-md;
      }

      &.is-correct {
        background-color: fade(@success, 8%);
        border-left: 3px solid @success;
      }

      .option-key-wrapper {
        display: flex;
        align-items: center;
        gap: 0.5rem;

        .drag-handle {
          color: @gray-400;
          cursor: move;
          padding: 0.25rem;
          transition: @transition;
          border-radius: @radius-sm;

          &:hover {
            color: @gray-600;
            background-color: @gray-100;
          }

          i {
            font-size: 0.875rem;
          }
        }

        .option-key {
          width: 36px;
          height: 36px;
          padding: 0.5rem;
          border: 1px solid @gray-300;
          border-radius: @radius-md;
          text-align: center;
          font-weight: 600;
          color: @primary;
          background-color: white;
          transition: @transition;
          font-family: @font-family;

          &:focus {
            outline: none;
            border-color: @primary;
            box-shadow: 0 0 0 3px fade(@primary, 20%);
          }
        }
      }

      .option-text-wrapper {
        flex: 1;
        min-width: 0;
      }

      .option-actions {
        display: flex;
        gap: 0.5rem;

        .btn-mark-correct,
        .btn-remove-option {
          position: relative;
          background: none;
          border: none;
          cursor: pointer;
          width: 36px;
          height: 36px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 50%;
          transition: @transition;

          &:disabled {
            opacity: 0.5;
            cursor: not-allowed;
          }

          i {
            font-size: 1rem;
          }
        }

        .btn-mark-correct {
          color: @success;
          background-color: fade(@success, 10%);

          &:hover {
            background-color: fade(@success, 20%);
          }

          .fa-check-circle {
            color: @success;
          }
        }

        .btn-remove-option {
          color: @danger;
          background-color: fade(@danger, 10%);

          &:hover {
            background-color: fade(@danger, 20%);
          }
        }
      }
    }

    .correct-answers {
      margin-top: 0.5rem;
      min-height: 100px;
      transition: height 0.3s ease;
      contain: content;

      .answer-options {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 0.75rem;

        @media (max-width: 768px) {
          grid-template-columns: 1fr;
        }
      }

      .answer-option {
        padding: 1rem;
        border-radius: @radius-md;
        border: 1px solid @gray-200;
        background-color: white;
        cursor: pointer;
        transition: @transition;
        display: flex;
        align-items: center;
        gap: 0.75rem;
        box-shadow: @shadow-sm;

        &:hover {
          border-color: @gray-300;
          transform: translateY(-2px);
          box-shadow: @shadow-md;
        }

        &.selected {
          background-color: fade(@primary, 8%);
          border-color: @primary;
          box-shadow: 0 0 0 1px @primary;

          .option-key {
            background-color: @primary;
            color: white;
          }
        }

        .option-key {
          width: 28px;
          height: 28px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 50%;
          background-color: @gray-100;
          color: @gray-700;
          font-weight: 600;
          font-size: 0.875rem;
          transition: @transition;
          flex-shrink: 0;
        }

        .option-preview {
          flex: 1;
          min-width: 0;
          font-size: 0.875rem;
          color: @gray-600;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .judgment-options {
        display: flex;
        gap: 1rem;

        @media (max-width: 768px) {
          flex-direction: column;
        }
      }

      .judgment-option {
        flex: 1;
        padding: 1.5rem 1rem;
        border-radius: @radius-md;
        border: 1px solid @gray-200;
        background-color: white;
        cursor: pointer;
        transition: @transition;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 0.75rem;
        box-shadow: @shadow-sm;

        &:hover {
          border-color: @gray-300;
          transform: translateY(-2px);
          box-shadow: @shadow-md;
        }

        &.selected {
          background-color: fade(@primary, 8%);
          border-color: @primary;
          box-shadow: 0 0 0 1px @primary;

          .judgment-icon {
            background-color: @primary;
            color: white;
          }
        }

        .judgment-icon {
          width: 48px;
          height: 48px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 50%;
          background-color: @gray-100;
          transition: @transition;
          flex-shrink: 0;
          box-shadow: @shadow-sm;

          i {
            font-size: 1.25rem;
          }
        }

        .judgment-label {
          font-weight: 500;
          color: @gray-700;
        }
      }

      .true-option {
        &.selected {
          border-color: @success;
          background-color: fade(@success, 8%);
          box-shadow: 0 0 0 1px @success;

          .judgment-icon {
            background-color: @success;
          }
        }
      }

      .false-option {
        &.selected {
          border-color: @danger;
          background-color: fade(@danger, 8%);
          box-shadow: 0 0 0 1px @danger;

          .judgment-icon {
            background-color: @danger;
          }
        }
      }

      .fill-blank-answer {
        .answer-input {
          input {
            width: 100%;
            padding: 0.875rem 1rem;
            border: 1px solid @gray-300;
            border-radius: @radius-md;
            font-size: 0.9375rem;
            color: @gray-800;
            transition: @transition;
            background-color: white;
            font-family: @font-family;
            box-shadow: @shadow-sm;

            &:focus {
              outline: none;
              border-color: @primary;
              box-shadow: 0 0 0 3px fade(@primary, 20%);
            }

            &::placeholder {
              color: @gray-400;
              font-size: 0.875rem;
            }
          }
        }
      }
    }
  }

  .dialog-footer {
    padding: 1.25rem 2rem;
    border-top: 1px solid @gray-200;
    display: flex;
    justify-content: flex-end;
    gap: 1rem;
    background-color: white;

    .btn {
      padding: 0.75rem 1.5rem;
      border-radius: @radius-md;
      font-weight: 500;
      cursor: pointer;
      transition: @transition;
      border: none;
      font-size: 0.9375rem;
      min-width: 120px;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 0.5rem;
      box-shadow: @shadow-sm;

      &.btn-secondary {
        background-color: white;
        color: @gray-700;
        border: 1px solid @gray-300;

        &:hover {
          background-color: @gray-100;
          transform: translateY(-1px);
          box-shadow: @shadow-md;
        }

        &:active {
          transform: translateY(0);
        }
      }

      &.btn-primary {
        background: @primary;
        color: white;
        box-shadow: @shadow-md;

        &:hover {
          background: darken(@primary, 5%);
          transform: translateY(-1px);
          box-shadow: @shadow-lg;
        }

        &:active {
          transform: translateY(0);
        }

        &:disabled {
          opacity: 0.7;
          cursor: not-allowed;
          background: @gray-400;
          transform: none;
        }
      }

      i {
        font-size: 0.875rem;
      }
    }
  }
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes dialogEnter {
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

@media (max-width: 768px) {
  .question-edit-dialog {
    .dialog-container {
      width: 95%;
      max-width: 95%;
      max-height: 90vh;
    }

    .dialog-body {
      padding: 1.5rem;
    }

    .dialog-footer {
      flex-direction: column-reverse;

      .btn {
        width: 100%;
      }
    }

    .form-group.type-selector .type-options {
      grid-template-columns: repeat(2, 1fr);
    }
  }
}

/* 添加一些微交互效果 */
.answer-option,
.judgment-option,
.option-item {
  will-change: transform;
  backface-visibility: hidden;
  transform: translateZ(0);
}

/* 加载动画 */
@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.is-saving {
  animation: pulse 1.5s infinite;
}

/* 优化移动端体验 */
@media (max-width: 480px) {
  .dialog-header {
    padding: 1rem;
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;

    .header-actions {
      width: 100%;
      justify-content: space-between;
    }
  }

  .form-group.type-selector .type-options {
    grid-template-columns: 1fr 1fr;
  }

  .option-item {
    flex-direction: column;
    align-items: stretch;
    gap: 0.5rem;

    .option-key-wrapper {
      justify-content: space-between;
    }

    .option-actions {
      justify-content: flex-end;
    }
  }
}

/* 添加一些细节效果 */
.option-key {
  transition: all 0.2s ease;
}

.answer-option.selected .option-key {
  transform: scale(1.1);
}

/* 优化文本区域 */
textarea {
  line-height: 1.6;
  &::placeholder {
    transition: opacity 0.2s ease;
  }
  &:focus::placeholder {
    opacity: 0.5;
  }
}

/* 添加一些状态反馈 */
.is-correct {
  position: relative;
  &::after {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 0 24px 24px 0;
    border-color: transparent @success transparent transparent;
  }
}


.drag-handle {
  touch-action: none;
}

/* 添加一些微妙的背景图案 */
.dialog-body {
  background-image:
      radial-gradient(circle at 1px 1px, @gray-200 1px, transparent 0);
  background-size: 10px 10px;
  background-color: @gray-50;
}

/* 优化按钮点击效果 */
.btn {
  user-select: none;
  &:active {
    transition: none;
    filter: brightness(0.95);
  }
}

/* 添加一些辅助视觉元素 */
.form-group {
  position: relative;
  &:not(:last-child)::after {
    content: '';
    position: absolute;
    bottom: -0.75rem;
    left: 0;
    right: 0;
    height: 1px;
    background-color: fade(@gray-200, 50%);
  }
}

/* 优化滑动输入条 */
.slider-input {
  &::-webkit-slider-thumb {
    transition: transform 0.1s ease;
  }
  &:active::-webkit-slider-thumb {
    transform: scale(1.2);
  }
}
</style>